<?php

namespace Admin\Controller;
use Admin\Builder\AdminListBuilder;
use Admin\Builder\AdminConfigBuilder;
use Weisite\Builder\WeisiteCategoryBuilder;

class WeisiteController extends AdminController {
    protected function msuccess($msg = '保存成功', $url = ''){
        header('Content-type: application/json');
        $url = $url ? $url : __SELF__;
        exit(json_encode(array('info' => $msg, 'status' => 1, 'url' => $url)));
    }
    protected function merror($msg = '保存失败', $url = ''){
        header('Content-type: application/json');
        $url = $url ? $url : __SELF__;
        exit(json_encode(array('info' => $msg, 'status' => 0, 'url' => $url)));
    }

	function index() {
        $builder = new AdminConfigBuilder();
        $data = $builder->handleConfig();

        $siteurl = 'http://' . $_SERVER['HTTP_HOST'] . U('Weisite/Index/index');
    
        $builder->title('微网设置')->suggest('<a href="' . $siteurl . '" target="_blank" style="font-size: 12px;">首页地址：' . $siteurl . '</a>');
        $builder->keyText('SITE_TITLE', '网站名');
        $builder->keySingleImage('BACKGROUND', '模板背景图', '为空时默认使用模板里的背景图片');
        $builder->keyTextArea('CODE', '统计代码');

        $builder->data($data);
        $builder->keyDefault('SUCCESS_WAIT_TIME',2);
        $builder->keyDefault('ERROR_WAIT_TIME',3);

        $builder->buttonSubmit();
        $builder->display();
	}
    
    public function news($page=1,$r=10){
        $builder = new AdminListBuilder();
        $builder->title("新闻列表");
        $where = array(
            'is_news' => 1
        );

        if(I('get.cid')){
            $where['cid'] = I('get.cid');
        }

        $reportCount = $this->getAreplyModel()->where($where)->count();
        $list = $this->getAreplyModel()->page($page,$r)->field('id,title,image,cid')->where($where)->order('id DESC')->select();
        $cat = $this->getNewsCat();

        $builder
            ->keyId()
            ->keyImage('image', "封面")
            ->keyMap('cid', "类别", $cat)
            ->keyText('title', "标题")
            ->keyText('keywords', "回复关键词")
            ->keyDoActionEdit('Weisite/editnews?id=###')
            ->buttonDelete(U('delnews'));

        $builder->buttonNew(U('editnews'), '添加新闻');

        $builder->data($list);
        $builder->pagination($reportCount, $r);
        $builder->display();
    }
    
    protected function getAreplyModel(){
        return D('Weisite/WeisiteNews');
    }

    public function delnews(){
        $id = I('post.ids');

        if($id){
            $rs = false;
            foreach($id as $item){
                if(intval($item)){
                    $rs = $this->getAreplyModel()->delete($item) || $rs;
                }
            }
            if($rs){
                $this->msuccess('删除成功', U('news'));
            }
        }
        $this->msuccess('删除失败', U('news'));
    }

    public function editnews(){
        $id = I('get.id');
        if(IS_POST){
            $id = I('post.id');
            $data = I('post.');
            $data['type'] = 2;
            $data['is_news'] = 1;
            $data['ctime'] = time();
            $mod = $this->getAreplyModel();
            $mod->create($data);
            if($id){
                $rs = $mod->save();
            } else {
                $rs = $mod->add();
            }
            if($rs){
                $this->msuccess();
            } else {
                $this->merror();
            }
        }

        $cat = $this->getNewsCat();
        $builder = new AdminConfigBuilder();
        $data = $this->getAreplyModel()->find($id);
        $builder->keyId();
        $builder->title('新闻管理');
        $builder->keyText('keywords', '回复关键词', '非自动回复请保持为空');
        $builder->keyText('title', '标题');
        $builder->keySelect('cid', '类别', null, $cat);
        $builder->keySingleImage('image', '封面图片');
//        $builder->keyText('linkurl', '链接', '可不填');
        $builder->keyEditor('content', '回复内容');

        $builder->data($data);
        $builder->keyDefault('SUCCESS_WAIT_TIME',2);
        $builder->keyDefault('ERROR_WAIT_TIME',3);

        $builder->buttonSubmit();
        $builder->display();
    }

    protected function getNewsCat(){
        $options = S('WX_ADMIN_CATEGORY_OPTIONS');
        if(!$options){
            $category= D('Weisite/WeisiteCategory')->getCategoryList(array('is_show'=>array('egt',0)),1);
            $options=array();
            foreach($category as $val){
                $options[$val['id']]=$val['title'];
            }
            
            S('WX_ADMIN_CATEGORY_OPTIONS', $options);
        }
        return $options;
    }

    function category(){
        //显示页面
        $builder = new WeisiteCategoryBuilder();
        $tree = D('Weisite/WeisiteCategory')->getTree(0, 'id,title,icon,url,sort,pid,is_show, is_menu');
        $builder->title('分类、导航管理')
            ->suggest('如果子菜单要显示，请设置父菜单为菜单显示，最多2级')
            ->buttonNew(U('categoryadd'))
            ->data($tree)
            ->display();
    }
    
    public function categoryadd($id = 0, $pid = 0)
    {
        $title=$id?"编辑":"新增";
        $categoryMod = D('Weisite/WeisiteCategory');
        if (IS_POST) {
            if ($categoryMod->editData()) {
                $this->success($title.'成功。', U('category'));
            } else {
                $this->error($title.'失败!'.$categoryMod->getError());
            }
        } else {
            $builder = new AdminConfigBuilder();

            if ($id != 0) {
                $data = $categoryMod->find($id);
            } else {
                $father_category_pid=$categoryMod->where(array('id'=>$pid))->getField('pid');
                if($father_category_pid!=0){
                    $this->error('菜单不能超过二级！');
                }
            }
            if($pid!=0){
                $categorys = $categoryMod->where(array('pid'=>0,'status'=>array('egt',0)))->select();
            }
            $opt = array();
            foreach ($categorys as $category) {
                $opt[$category['id']] = $category['title'];
            }
            $builder->title($title.'分类')
                ->data($data)
                ->keyId()->keyText('title', '标题')
                ->keySelect('pid', '父分类', '选择父级分类', array('0' => '顶级菜单') + $opt)->keyDefault('pid',$pid)
                ->keySingleImage('icon','图标')->keyDefault('sort',0)
                ->keyText('url','链接地址(默认不设置)')->keyDefault('sort',0)
                ->keyInteger('sort','排序')->keyDefault('sort',0)
                ->keyStatus('is_show')->keyDefault('is_show',1)
                ->keyBool('is_menu', '是否是菜单')
                ->buttonSubmit(U('categoryadd'))->buttonBack()
                ->display();
        }
    }
    
    public function categorydel(){
        $id = I('get.id');
        if($id && D('Weisite/WeisiteCategory')->delete($id)){
            D('Weisite/WeisiteCategory')->where(array('pid' => $id))->save(array('pid' => 0));
            $this->msuccess('删除成功', U('category'));
        } else {
            $this->merror('删除失败', U('category'));
        }
    }
    
    protected function getSlideModel(){
        return D('weisiteSlideshow');
    }
    
    public function slideshow($page=1,$r=10){
        $builder = new AdminListBuilder();
        $builder->title("首页幻灯片");

        $reportCount = $this->getSlideModel()->count();
        $list = $this->getSlideModel()->page($page,$r)->order('id DESC')->select();
     
        $builder
            ->keyId()
            ->keyText('title', "标题")
            ->keyImage('img', "图片")
            ->keyText('url', "链接地址")
            ->keyStatus('is_show', '显示')
            ->keyDoActionEdit('Weisite/slideadd?id=###')
            ->buttonDelete(U('slidedel'));

        $builder->buttonNew(U('slideadd'), '新增幻灯片');
        
        $builder->data($list);
        $builder->pagination($reportCount, $r);
        $builder->display();
    }
    
    protected function slideSave($dataSet = array()){
        if(IS_POST){
            $id = I('post.id');
            $data = I('post.');

            $data = array_merge($data, $dataSet);
            $mod = $this->getSlideModel();
            $mod->create($data);
            if($id){
                $rs = $mod->save();
            } else {
                $rs = $mod->add();
            }
            if($rs){
                $this->msuccess();
            } else {
                $this->merror();
            }
        }
    }

    public function slideadd(){
        $id = I('get.id');
        $title = $id ? '修改' : '新增';
        $this->slideSave($dataSet);

        $builder = new AdminConfigBuilder();
        $data = $this->getSlideModel()->find($id);
        $builder->keyId();
        $builder->title($title . '首页幻灯片');
        $builder->keyText('title', '标题');
        $builder->keySingleImage('img', '图片');
        $builder->keyText('url', '链接地址 ');
        $builder->keyStatus('is_show', '是否显示');

        $builder->data($data);
        $builder->keyDefault('SUCCESS_WAIT_TIME',2);
        $builder->keyDefault('ERROR_WAIT_TIME',3);

        $builder->buttonSubmit();
        $builder->display();
    }
    
    public function slidedel(){
        $id = I('post.ids');
        if($id){
            $rs = false;
            foreach($id as $item){
                if(intval($item)){
                    $rs = $this->getSlideModel()->delete($item) || $rs;
                }
            }
            if($rs){
                $this->getSlideModel()->where(array('pid' => $id))->save(array('pid' => 0));
                $this->msuccess('删除成功', U('slideshow'));
            }
        } else {
            $this->merror('删除失败', U('slideshow'));
        }
    }

    // 获取目录下的所有模板
    public function template() {
        $config = $this->getWeisiteConfig();
      
        $type = I('get.type', 'index');
        
        $template_type = 'Template' . ucfirst($type);
        $template_root = __DIR__ . '/../View/default/';
        $template_url =  __ROOT__ . '/Application/' . CONTROLLER_NAME . '/View/default/';
        $dir = $template_root . $template_type;
        
        $default = $config['TEMPLATE_' . strtoupper($type)];
        
        $dirObj = opendir ( $dir );
        while ( $file = readdir ( $dirObj ) ) {
            if ($file === '.' || $file == '..' || $file == '.svn' || is_file ( $dir . '/' . $file ))
                continue;
            $res ['dirName'] = $res ['title'] = $file;
            // 获取配置文件
            if (file_exists ( $dir . '/' . $file . '/info.php' )) {
                $info = require_once $dir . '/' . $file . '/info.php';
                $res = array_merge ( $res, $info );
            }

            // 获取效果图
            if (file_exists ( $dir . '/' . $file . '/info.php' )) {
                $res ['icon'] = $template_url . $template_type . '/' . $file . '/icon.png';
            } else {
                $res ['icon'] = $template_url . 'Public/default.png';
            }
            
            // 默认选中
            if ($default == $file) {
                $res ['class'] = 'selected';
                $res ['checked'] = 'checked="checked"';
            }

            $tempList [] = $res;
            unset ( $res );
        }
        closedir ( $dir );
        // dump ( $tempList );
        $this->assign ( 'admin_css', $template_url . 'Public/css.css' );
        $this->assign ( 'tempList', $tempList );
        
        $types = array(
            'index' => '首页',
            'lists' => '图文列表',
            'detail' => '图文内容',
            'footer' => '底部菜单',
        );
        $this->assign('types', $types);
        $this->assign('type', $type);
        $this->display(T('Weisite@Admin/template'));
    }

    protected function getWeisiteConfig(){
        $builder = new AdminConfigBuilder();
        $data = $builder->handleConfig();

        return $data;
    }

}